package akka

import akka.actor.{Actor, ActorSystem, Props}
import akka.event.Logging

/**
  * Created by shichen on 2017/7/21.
  * code from Learning Concurrent Programming in Scala chapter8 Actors
  */

class ChildActor extends Actor {
  val log = Logging(context.system,this)
  override def receive: Receive = {
    case "sayhi" =>
      val parent = context.parent
      log.info(s"my parent $parent made me say hi")
  }

  override def postStop(): Unit = {
    log.info("child stopped")
  }
}


class ParentActor extends Actor {
  val log = Logging(context.system,this)
  override def receive: Receive = {
    case "create" =>
      context.actorOf(Props[ChildActor])
      log.info(s"created a kid, kids = ${context.children}")
    case "sayhi" =>
      log.info("ask kid to say hi")
      for (c <- context.children) c ! "sayhi"
    case "stop" =>
      log.info("stop parent")
      context.stop(self)
  }
}
object ActorHierarchy extends App{
  val sys = ActorSystem("ActorHierarchy")
  val parent = sys.actorOf(Props[ParentActor],"parent")
  parent ! "create"
  parent ! "create"
  Thread.sleep(1000)

  parent ! "sayhi"
  Thread.sleep(1000)
  parent ! "stop"
  Thread.sleep(1000)

  sys.terminate()
}
